from app.models import Student, User
from werkzeug.security import generate_password_hash, check_password_hash
from app.extensions import db
from app.services.plan_config_service import PlanConfigService
import random
import string
from flask import current_app
from datetime import datetime
class StudentService:
    """学生管理服务"""

    @staticmethod
    def get_student_account_info(student_id: int):
        student = Student.query.get(student_id)
        user = User.query.get(student.user_id)
        # 还原密码为明文


        if not user:
            return {'code': 404, 'msg': '用户不存在'}
        return {
            'code': 200, 'data': {
            'student_id': student.student_id,
            'username': user.username,
            'password': user.password,
            'name': student.name,
            'stage_tag': student.stage_tag,
            'create_time': student.create_time.strftime('%Y-%m-%d %H:%M:%S'),
        }}


    @staticmethod
    def create_student(parent_id: int, name: str, stage_tag: str = None) -> dict:
        """
        创建学生账号（自动生成凭证）
        """
        def generate_username():
            """生成唯一学号 (STU+8位数字)"""
            max_attempts = 5
            for _ in range(max_attempts):
                # 获取当前最大用户ID作为基数
                max_id = db.session.query(db.func.max(User.user_id)).scalar() or 0
                username = f"STU{(max_id + 1):08d}"
                if not User.query.filter_by(username=username).first():
                    return username
            raise ValueError("无法生成唯一用户名，请稍后重试")

        def generate_password(length=10):
            """生成包含大小写字母和数字的随机密码"""
            chars = string.ascii_letters + string.digits
            return ''.join(random.choice(chars) for _ in range(length))

        try:
            # 1. 验证家长用户是否存在
            parent = User.query.filter_by(user_id=parent_id, role='家长').first()
            if not parent:
                current_app.logger.warning(f"无效的家长ID: {parent_id}")
                return {'code': 400, 'msg': '家长账号不存在'}

            # 2. 生成学生凭证
            username = generate_username()
            password = generate_password()
            hashed_password = generate_password_hash(password)

            # 3. 创建学生用户账号
            student_user = User(
                username=username,
                password=hashed_password,
                role='学生',  # 注意与枚举值一致
                reg_time=datetime.now()
                # mobile和email允许为NULL，无需设置
            )
            db.session.add(student_user)
            db.session.flush()  # 获取user_id

            # 4. 创建学生档案
            new_student = Student(
                name=name,
                stage_tag=stage_tag,
                user_id=student_user.user_id,
                parent_id=parent_id,
                create_time=datetime.now()
            )
            db.session.add(new_student)
            db.session.flush()

            # 5. 初始化学习计划
            PlanConfigService.create_default_config(new_student.student_id)

            db.session.commit()

            current_app.logger.info(
                f"成功创建学生: 学生ID={new_student.student_id}, "
                f"用户名={username}, 家长ID={parent_id}"
            )

            return {
                'code': 200,
                'msg': '学生创建成功',
                'data': {
                    'student_id': new_student.student_id,
                    'username': username,
                    'password': password  # 注意：实际应用中应通过安全方式传递
                }
            }

        except ValueError as e:
            db.session.rollback()
            current_app.logger.error(f"生成用户名失败: {str(e)}")
            return {'code': 400, 'msg': str(e)}
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(
                f"创建学生失败: {type(e).__name__}: {str(e)}", 
                exc_info=True
            )
            return {'code': 500, 'msg': '系统错误，请稍后重试'}


    @staticmethod
    def get_student_list(parent_id: int) -> dict:
        """获取家长名下学生列表"""
        students = Student.query.filter_by(parent_id=parent_id).all()
        if not students:  # 如果没有找到学生
            return {'code': 404, 'message': 'No students found', 'data': None}
        return {'code': 200, 'data': [s.to_dict() for s in students]}

    @staticmethod
    def update_student_info(student_id: int, **kwargs) -> dict:
        """更新学生信息"""
        student = Student.query.get(student_id)
        if not student:
            return {'code': 404, 'msg': '学生不存在'}
        
        if 'name' in kwargs:
            student.name = kwargs['name']
        if 'stage_tag' in kwargs:
            student.stage_tag = kwargs['stage_tag']
        
        db.session.commit()
        return {'code': 200, 'msg': '学生信息已更新'}
    
    @staticmethod
    def delete_student(student_id: int) -> dict:
        """删除学生"""
        student = Student.query.get(student_id)
        if not student:
            return {'code': 404, 'msg': '学生不存在'}
        
        db.session.delete(student)
        db.session.commit()
        return {'code': 200, 'msg': '学生已删除'}
    
    @staticmethod
    def delete_students(student_ids: list) -> dict:
        """删除多个学生"""
        students = Student.query.filter(Student.student_id.in_(student_ids)).all()
        if not students:
            return {'code': 404, 'msg': '学生不存在'}
        
        for student in students:
            db.session.delete(student)
        db.session.commit()
        return {'code': 200, 'msg': '学生已删除'}